import "./index.less"
import { Space, Table, Tag, Input, Button, message, TablePaginationConfig, Modal, Form, Switch } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { getCustomer, addCustomer, updateCustomer } from "@/api/account"
import { useEffect, useRef, useState } from "react";
import systme from "@/api/constant"



interface DataType {
    account: string
    address: string
    createDate: string
    id: string
    loginDate: string
    pageIndex: number
    pageSize: number
    password: string
    userName: string
}

interface paramsType {
    userName: string,
    account: string,
    address: string,
    person: personType
    password: string

}
interface personType {
    email: string
    phone: string
    realName: string
    sex: string
}


const confirm = () => {

}
const cancel = () => {
    message.info("取消了删除操作")
}








const searchValue = {
    userName: '',
    account: '',
    address: '',
    pageIndex: 1,
    pageSize: 10
}

let customerId: string;
let personId: string


export default function customer() {

    useEffect(() => {
        getCustomerList()
    }, [])
    const [data, setData] = useState<DataType[]>([])

    const columns: ColumnsType<DataType> = [
        {
            title: '账号',
            dataIndex: 'account',
            key: 'account',
        },
        {
            title: '客户名',
            dataIndex: 'userName',
            key: 'userName',

        },

        {
            title: '客户所在地',
            dataIndex: 'address',
            key: 'address',
        },
        {
            title: '最后登录日期',
            key: 'loginDate',
            render: (_, record: DataType) => (
                <Space size="middle">
                    <div>
                        {record.loginDate.slice(0, 10)}
                    </div>
                </Space>
            )


        },
        {
            title: '操作',
            key: 'action',
            render: (_, record:any) => (
                <Space size="middle">
                    <a onClick={()=> {handlerMessage(record)}}>联系人信息</a>
                    <a style={{ 'color': 'green' }} onClick={() => { handlerEdit(record) }}>编辑</a>
                </Space>
            ),
        },
    ];


    const getCustomerList = (data = searchValue) => {
        getCustomer(data).then((res) => {
            if (res.code == 200) {
                setData(res.data.list)
                setConfig({ ...saveValue.current, total: res.data.total })
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
            }
            setLoading(false)
        }).catch((error) => {
            message.error(error || systme.ERROR_MESSAGE)
            setLoading(false)
        })

    }
    const handlerSearch = (e: any) => {
        searchValue.userName = e.target.value as string
    }
    const search = () => {
        setLoading(true)
        getCustomerList(searchValue)
    }
    const PageChange = (page: number, pageSize: number) => {
        searchValue.pageIndex = page
        searchValue.pageSize = pageSize
        setLoading(true)
        setConfig({ ...saveValue.current, pageSize, current: page })
        getCustomerList()
    }

    let pageConfig: TablePaginationConfig = {
        position: ['bottomCenter'],
        total: 0,
        showTotal: (total: number) => `共 ${total} 条`,
        pageSizeOptions: [10, 20, 30, 40, 50],
        showSizeChanger: true,
        showQuickJumper: true,
        onChange: PageChange,
        pageSize: 10,
        current: 1

    }
    let [config, setConfig] = useState((pageConfig))
    let saveValue = useRef<TablePaginationConfig>()
    useEffect(() => {
        //储存数据
        saveValue.current = config
    }, [config])
    //弹窗
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalOpen2, setIsModalOpen2] = useState(false);

    const handleOk = () => {
        if (title == "创建客户") {
            handlerCustomer()
        } else if (title == "编辑客户信息") {
            handlereditCustomer()
        }
    };

    const handleOk2 = () => {
        setIsModalOpen2(false)
    };
    const handleCancel2 = () => {
        setIsModalOpen2(false)
    };

    //处理数据格式
    const handlerFormate = (data: any) => {
        let personKey = ['realName', 'email', 'phone', 'sex']
        let params = {
            person: {}
        }
        for (let key in data) {
            if (personKey.indexOf(key) != -1) {
                if (key == 'sex') {
                    (params as any).person[key] = data[key] ? '男' : '女'
                } else {
                    (params as any).person[key] = data[key] || ''
                }
            } else {
                (params as any)[key] = data[key] || ''
            }
        }

        return params
    }
    const initData = () => {
        searchValue.pageIndex = 1
        searchValue.account = ''
        searchValue.userName = ''
        searchValue.address = ''
        getCustomerList()

    }

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    //添加员工
    const [title, settitle] = useState<string>('创建客户')
    const handlerAdd = () => {
        settitle('创建客户')
        form.resetFields();
        setIsModalOpen(true);
    }
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(true)
    const handlerCustomer = () => {
        form.validateFields().then((values) => {
            let params = handlerFormate(values)
            addCustomer(params).then((res) => {
                if (res.code == 200) {
                    message.success("添加成功")
                    setIsModalOpen(false)
                    //清除表单数据
                    form.resetFields();
                    initData()
                } else {
                    message.error(res.msg || "添加失败")
                }
            })
        }).catch(() => {
            message.error("存在未输入的值")
        })
    }

    //编辑
    const handlerEdit = (e: any) => {
        customerId = e.id
        personId = e.person.id
        settitle('编辑客户信息')
        let resolveData = resloveFormate(e)
        form.setFieldsValue(resolveData)
        setIsModalOpen(true);

    }
    const resloveFormate = (data: any) => {
        let params = {} as any

        for (let key in data.person) {
            params[key] = data.person[key] || ''
        }

        for (let key in data) {
            if (key != 'person') {
                params[key] = data[key] || ''
            }
        }
        return params
    }
    const handlereditCustomer = () => {
        form.validateFields().then((values) => {
            let params: any = handlerFormate(values)
            params.id = customerId
            params.person.id = personId
            updateCustomer(params).then((res) => {
                if (res.code == 200) {
                    message.success("修改成功")
                    setIsModalOpen(false)
                    //清除表单数据
                    form.resetFields();
                    initData()
                } else {
                    message.error(res.msg || "修改失败")
                }
            })
        }).catch(() => {
            message.error("存在未输入的值")
        })

    }

    let [personInfo,setPersonInfo] = useState<personType>()
    //查看联系人信息
    const handlerMessage = (data:paramsType) => {
        setPersonInfo(data.person)
        setIsModalOpen2(true);
    }


    return (
        <div className="box_views">
            <div className="header flex">
                <div className="header_search flex">
                    <div className="item">
                        <Input placeholder="请输入客户姓名" allowClear onChange={(e: unknown) => { handlerSearch(e) }} />
                    </div>
                    <Button type="primary" icon={<SearchOutlined />} size="middle" onClick={search}>查询</Button>

                </div>
                <div className="addBtn">
                    <Button type="primary" icon={<PlusOutlined />} size="middle" onClick={handlerAdd}>创建客户</Button>
                </div>
            </div>
            <Table columns={columns} dataSource={data} pagination={config} rowKey={item => item.id} loading={loading} />
            <Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width="800px">
                <div className="form">
                    <Form
                        name="basic"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        style={{ maxWidth: 600 }}
                        form={form}
                    >
                        <Form.Item
                            label="账号"
                            name="account"
                            rules={[{ required: true, message: '请输入账号' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="客户名"
                            name="userName"
                            rules={[{ required: true, message: '请输入客户名' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="联系人"
                            name="realName"
                            rules={[{ required: true, message: '请输入联系人' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="地址"
                            name="address"
                            rules={[{ required: true, message: '请输入地址' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="邮箱"
                            name="email"
                            rules={[{ required: true, message: '请输入邮箱' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="手机号"
                            name="phone"
                            rules={[{ required: true, message: '请输入手机号' }]}
                        >
                            <Input />
                        </Form.Item>
                        {
                            title == "创建客户" && <Form.Item
                                label="密码"
                                name="password"
                                rules={[{ required: true, message: '请输入密码' }]}
                            >
                                <Input />
                            </Form.Item>
                        }
                        <Form.Item
                            label="性别"
                            name="sex"
                            valuePropName="checked"
                        >
                            <Switch checkedChildren="男" unCheckedChildren="女" />
                        </Form.Item>
                    </Form>
                </div>
            </Modal>
            <Modal title="联系人信息" open={isModalOpen2} onOk={handleOk2} onCancel={handleCancel2}  centered>
                <div className="flex_j_c">
                    <div className="personItem">
                         姓名：{personInfo?.realName}
                    </div>
                    <div className="personItem">
                        邮箱：{personInfo?.email}
                    </div>
                    <div className="personItem">
                        手机号：{personInfo?.phone}
                    </div>
                    <div className="personItem">
                        性别：{personInfo?.sex}
                    </div>
                </div>
            </Modal>
        </div>
    )
}